<template>
  <div class="adInvoice-report-list table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable ref="filterTable" :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="outline" size="medium" @click="onTestPullInvoice">检验授权状态</a-button>
            <a-button type="outline" size="medium" @click="openCheckedDialog">核销</a-button>
            <a-button class="gray-outline" size="medium" @click="onUnDoCheckBatch">取消核销</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            :data="tableList"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :summary="true"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :bordered="{ headerCell: true }"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="核销月份" :width="90" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <p v-if="record.bookMonth">
                    <span v-if="record.checkStatus === 0">*</span>
                    <span>{{ record.bookMonth }}</span>
                  </p>
                </template>
              </a-table-column>
              <a-table-column title="店名" :width="160">
                <template #cell="{ record }">
                  <p>{{ getShopName(record) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="站点" :width="60" data-index="marketplaceId">
                <template #cell="{ record }">
                  <span>{{ $extract(marketPlaceList[record.marketplaceId], 'code') }}</span>
                </template>
              </a-table-column>
              <a-table-column title="账单日期" data-index="invoiceDate" :width="90" align="right" :sortable="sortable" />
              <a-table-column title="发票号" :width="120">
                <template #cell="{ record }">
                  <p class="highlight cursor" @click="openDetail(record)">{{ record.invoiceId }}</p>
                </template>
              </a-table-column>
              <a-table-column title="币种" data-index="dueCurrency" :width="70" />
              <a-table-column title="票额" data-index="dueAmt" :width="80" :sortable="sortable" align="right" />
              <a-table-column title="明细" data-index="totalItemAmt" :width="80" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <span v-if="record.totalItemAmt">{{ record.totalItemAmt }}</span>
                  <a-button size="mini" class="gray-outline" v-else @click="onPullInvoiceItem(record)">拉取</a-button>
                </template>
              </a-table-column>
              <a-table-column title="明细分配" data-index="fp" :width="400" :sortable="sortable">
                <template #cell="{ record }">
                  <span class="sales-man" v-for="(item, amtindex) in record.totalItemAmtDetail" :key="amtindex">
                    <span class="sales-man-name">{{ item.salesmanName ? item.salesmanName : '未知' }}</span>
                    <span class="sales-man-amt">{{ item.amt }}</span>
                  </span>
                </template>
              </a-table-column>
              <a-table-column title="调整" data-index="adjustmentsAmt" :width="120" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <a-popover v-if="record.adjustmentsAmt != 0" placement="bottom" width="600" trigger="hover">
                    <template #content>
                      <ul class="adjustments-list-header flex-c-sb">
                        <li style="width: 50px">类型</li>
                        <li style="width: 420px">描述</li>
                        <li style="width: 80px">金额</li>
                      </ul>
                      <ul class="adjustments-list-con">
                        <li v-for="(item, index) in record.adjustmentsList" :key="index" class="flex-c-sb">
                          <div style="width: 50px">
                            {{ item.type === 1 ? '调整' : '优惠' }}
                          </div>
                          <div style="width: 420px">{{ item.description }}</div>
                          <div style="width: 80px">{{ item.amt }}</div>
                        </li>
                      </ul>
                    </template>
                    <div class="cursor">
                      {{ record.adjustmentsAmt }}
                      <a-button class="gray-outline" v-if="record.taxDueCurrency === 'JPY' && record.dueAmt != record.totalItemAmt" @click="onShowAddAdJustmentDialog(record)" size="mini"> + </a-button>
                    </div>
                  </a-popover>
                  <div v-else>
                    {{ record.adjustmentsAmt }}
                    <a-button class="gray-outline" v-if="record.taxDueCurrency === 'JPY' && record.dueAmt != record.totalItemAmt" @click="onShowAddAdJustmentDialog(record)" size="mini"> + </a-button>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="调整分配" data-index="fp" :width="300" :sortable="sortable">
                <template #cell="{ record }">
                  <div v-if="record.adjustmentsAmt != 0">
                    <a-button class="gray-outline" @click="onShowAdjustmentDistubutionDialog(record)" size="mini"> 分配 </a-button>
                    <span class="sales-man" style="width: auto" v-for="(item, amtindex) in record.accItemList" :key="amtindex" v-show="item.type != 'TAX'">
                      <span class="sales-man-name">{{ item.salesmanName ? item.salesmanName : '未知' }}</span>
                      <span class="sales-man-amt">{{ item.amt }}</span>
                    </span>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="税额" data-index="taxDueAmt" :width="80" :sortable="sortable" />
              <a-table-column title="税额分配" data-index="fp" :width="200" :sortable="sortable">
                <template #cell="{ record }">
                  <div v-if="record.taxDueAmt != 0">
                    <a-button class="gray-outline" @click="onShowTaxDistubutionDialog(record)" size="mini"> 分配 </a-button>
                    <span class="sales-man" style="width: auto" v-for="(item, amtindex) in record.accItemList" :key="amtindex" v-show="item.type === 'TAX'">
                      <span class="sales-man-name">{{ item.salesmanName ? item.salesmanName : '未知' }}</span>
                      <span class="sales-man-amt">{{ item.amt }}</span>
                    </span>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="开始时间" data-index="fromDate" :width="80" />
              <a-table-column title="结束时间" data-index="toDate" :width="80" />
              <a-table-column title="修改时间" data-index="gmtWrite" :width="90">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtWrite, 'MM-DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="发票状态" data-index="status" :width="110" />
            </template>
            <template #summary-cell="{ column, record }">
              <p v-if="column.dataIndex == 'sort'">合计</p>
              <p v-else-if="['dueAmt', 'totalItemAmt', , 'adjustmentsAmt', 'taxDueAmt'].includes(column.dataIndex)">{{ record[column.dataIndex].toFixed(2) }}</p>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <a-modal v-model:visible="addAdJustmentDialog" width="600px" top="8vh" ok-text="确认增加" title="增加调整项" title-align="start" :ok-loading="submitAdjustmentLoading" :on-before-ok="onSubmitAdjustment" :mask-closable="false">
    <div class="add-adjustment-w">
      <p class="adjustment-id">{{ currentData.id }}</p>
      <div class="flex-c item">
        <p class="label">发票</p>
        <h4 class="invoiceId">{{ currentData.invoiceId }}</h4>
      </div>
      <div class="flex-c item">
        <p class="label">发票额</p>
        <p> {{ currentData.dueAmt }}</p>
      </div>
      <div class="flex-c item">
        <p class="label">明细额</p>
        <p> {{ currentData.totalItemAmt }}</p>
      </div>
      <div class="flex-c item">
        <p class="label">调整金额</p>
        <a-input-number v-model="editAmt" style="width: 120px" />
      </div>
      <div class="flex-c item">
        <p class="label">说明</p>
        <a-textarea v-model="editRemarks" />
      </div>
    </div>
  </a-modal>
  <a-modal v-model:visible="testResultDialog" width="800px" :footer="false" title="测试结果" title-align="start" :mask-closable="false">
    <a-alert :closable="false"> 以下结果供技术人员使用</a-alert>
    <div style="max-height: calc(84vh - 160px); overflow-y: auto">
      {{ testBody }}
    </div>
  </a-modal>
  <a-modal v-model:visible="showCheckedDialog" width="500px" title="核销" title-align="start" :mask-closable="false" ok-text="确认核销" :on-before-ok="onConfirmCheckBatch">
    <a-month-picker v-model="currentBookMonth" format="YYYYMM" value-format="YYYYMM" placeholder="选择月" />
  </a-modal>
  <!-- 分配 -->
  <a-modal v-model:visible="showAdjustmentsDistubution" width="750px" title="调整&核销" title-align="start" :mask-closable="false" :footer="false">
    <div class="allot-w">
      <h4> 发票号：{{ currentData.invoiceId }} , 发票金额：{{ currentData.dueAmt }}, 币种：{{ currentData.dueCurrency }} </h4>
      <a-table class="table-normal-line" :data="currentData.totalItemAmtDetail" size="mini" :bordered="false" :pagination="false">
        <template #columns>
          <a-table-column data-index="salesmanName" title="运营" />
          <a-table-column data-index="amt" align="right" title="金额" />
        </template>
      </a-table>
      <a-alert :show-icon="false" :closable="false" type="success">该发票有部分调整金额需要分配</a-alert>
      <a-table class="table-normal-line" :data="currentData.adjustmentsList" size="mini" :bordered="false" :pagination="false">
        <template #columns>
          <a-table-column data-index="type" :width="80" title="类型">
            <template #cell="{ record }">
              {{ record.type === 1 ? '调整' : '优惠' }}
            </template>
          </a-table-column>
          <a-table-column data-index="description" title="描述" />
          <a-table-column data-index="amt" align="right" title="调整金额" :width="80" />
        </template>
      </a-table>
      <a-table style="margin-top: 10px" class="table-normal-line" :data="currentShopUserList" size="mini" :bordered="false" :pagination="false">
        <template #columns>
          <a-table-column data-index="salesmanName" title="运营" />
          <a-table-column :width="140" align="right" data-index="amt" title="金额">
            <template #cell="{ record }">
              <a-input-number size="mini" mode="button" v-model="record.amt" :precision="2" :step="0.01" :max="adjustmentTotalAmt < 0 ? 0 : adjustmentTotalAmt" :min="adjustmentTotalAmt < 0 ? adjustmentTotalAmt : 0" />
            </template>
          </a-table-column>
        </template>
      </a-table>

      <div style="color: red"> 提示：默认自动为按照运营人员费用花费比例均分,财务人员可以手动调整 </div>
      <h4> 开始时间 {{ currentData.fromDate }} 结束时间 {{ currentData.toDate }} </h4>
      <div style="margin-top: 10px" class="flex-c">
        <p>核入月份</p>
        <a-select style="width: 200px; margin-left: 5px" v-model="currentBookMonth" placeholder="">
          <a-option v-for="(item, index) in currentAllowMonth" :key="index" :value="item" :label="item" />
        </a-select>
      </div>
    </div>
    <div class="opt-button-layout" style="display: flex; justify-content: flex-end">
      <a-button type="primary" @click="onConfirmCheck('TZ')">确认分配(并核销入账)</a-button>
    </div>
  </a-modal>
  <!-- 税额调整 -->
  <a-modal v-model:visible="showTaxDistubution" width="800px" :footer="false" title="税额调整" title-align="start" :mask-closable="false">
    <div class="allot-w">
      <h4> 发票号：{{ currentData.invoiceId }} , 发票金额：{{ currentData.dueAmt }}, 币种：{{ currentData.dueCurrency }} 税额：{{ currentData.taxDueAmt }} </h4>
      <a-table class="table-normal-line" :data="currentData.totalItemAmtDetail" size="mini" :bordered="false" :pagination="false">
        <template #columns>
          <a-table-column data-index="salesmanName" title="运营" />
          <a-table-column data-index="amt" align="right" title="金额" />
        </template>
      </a-table>

      <a-alert :show-icon="false" :closable="false" type="success">
        <span>该发票有待分配税额</span>
        <span style="color: red; font-size: 20px">{{ currentData.taxDueAmt }}</span>
      </a-alert>
      <a-table style="margin-top: 10px" class="table-normal-line" :data="currentShopUserList" size="mini" :bordered="false" :pagination="false">
        <template #columns>
          <a-table-column data-index="salesmanName" title="运营" />
          <a-table-column :width="140" align="right" data-index="amt" title="金额">
            <template #cell="{ record }">
              <a-input-number size="mini" mode="button" v-model="record.amt" :precision="2" :step="0.01" :max="adjustmentTotalAmt < 0 ? 0 : adjustmentTotalAmt" :min="adjustmentTotalAmt < 0 ? adjustmentTotalAmt : 0" />
            </template>
          </a-table-column>
        </template>
      </a-table>
      <div style="color: red"> 提示：默认自动为按照运营人员费用花费比例均分,财务人员可以手动调整 </div>
      <h4> 开始时间 {{ currentData.fromDate }} 结束时间 {{ currentData.toDate }} </h4>
      <div style="margin-top: 10px" class="flex-c">
        <p>核入月份</p>
        <a-select style="width: 200px; margin-left: 5px" v-model="currentBookMonth" placeholder="">
          <a-option v-for="(item, index) in currentAllowMonth" :key="index" :value="item" :label="item" />
        </a-select>
      </div>
    </div>
    <div class="opt-button-layout" style="display: flex; justify-content: flex-end">
      <a-button type="primary" @click="onConfirmCheck('TAX')">确认分配(并核销入账)</a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, ref, computed, reactive } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import { invoiceFind, salesmanAmtCount, adjustmentsFind, adjustmentsDistribution, accItemFind, pullInvoiceItem, adjustmentsAdd, checkShopSpStatus, confirmCheck, undoCheck } from '@/api/finance/summaryReport'
  import { marketPlaceList } from '@/utils/globalData'
  import useUserStore from '@/store/modules/user'
  import { getShopMarketAndUserInfo } from '@/api/system'
  import useBaseDataStore from '@/store/modules/base-data'

  onMounted(async () => {
    getMarketList()
    await getShopList()
    setDefaultSearch()
  })
  const emit = defineEmits(['openDetail', 'toSearch'])
  const props = defineProps({
    searchVal: {
      type: Object,
      default: () => {},
    },
  })
  const searchVal = ref<any>({
    pageSize: 100,
    pageNum: 1,
  })
  const filterData = ref<any>({})
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const tableListMap = ref<any>({})
  const selectIds = ref([])
  const userStore = useUserStore()
  const tableRef = ref()
  const total = ref(0)
  const seachData = ref<any>({})
  const filterTable = ref()
  const currentData = ref<any>({})
  const editAmt = ref(0)
  const editRemarks = ref('')
  const addAdJustmentDialog = ref(false)
  const submitAdjustmentLoading = ref(false)
  const showAdjustmentsDistubution = ref(false)
  const showTaxDistubution = ref(false)
  const testBody = ref()
  const testResultDialog = ref(false)
  const showCheckedDialog = ref(false)
  const currentBookMonth = ref()
  const useBaseData = useBaseDataStore()
  const currentShopUserList = ref<Array<any>>([])
  const adjustmentTotalAmt = ref()
  const currentAllowMonth = ref<Array<any>>([])

  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
  }) as any

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplaceIdList',
      label: '站点',
      value: ref(props.searchVal.marketplaceIdList ? props.searchVal.marketplaceIdList?.split(',') : null),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'shopIdList',
      label: '全部店铺',
      value: ref(props.searchVal?.shopIdList ? props.searchVal.shopIdList.split(',') : null),
      type: 'select_multiple',
      width: 200,
      optionItems: [],
    },
    {
      key: 'checkStatus',
      label: '是否核销',
      value: ref('0'),
      type: 'select',
      width: 120,
      optionItems: [
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
    },

    {
      type: 'date_month',
      key: 'month',
      value: ref(),
      label: '账单月份',
      width: 140,
      attrs: {
        valueFormat: 'YYYYMM',
        placeholder: '账单月份',
      },
    },
    {
      type: 'date_month',
      key: 'bookMonth',
      value: ref(),
      label: '核入月份',
      width: 120,
      attrs: {
        valueFormat: 'YYYYMM',
        placeholder: '核入月份',
      },
    },
    {
      key: 'invoiceId',
      label: '发票号',
      value: ref(),
      type: 'input_search',
      width: 180,
    },
  ])
  const isAdmin = computed(() => userStore.admin)

  // 获取站点
  async function getMarketList() {
    await useBaseData.getMarketList()
    filterItem.value[0].optionItems = useBaseData.markedtList?.map((el: any) => {
      return {
        label: el.marketplaceName,
        value: el.marketplaceId,
      }
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    filterItem.value[1].optionItems = useBaseData.shopList?.map((el: any) => {
      return {
        label: el.shopName,
        value: el.id,
      }
    })
  }

  // 打开核销弹窗
  function openCheckedDialog() {
    if (!selectIds.value.length) {
      Message.error('请选择数据')
      return
    }
    currentBookMonth.value = ''
    showCheckedDialog.value = true
  }
  // 核销
  async function onConfirmCheckBatch() {
    let idList = selectIds.value.filter((id: string) => tableListMap.value[id].adjustmentsAmt != -1)
    let param = {
      adInvoiceIdList: idList,
      bookMonth: currentBookMonth.value,
      useAutoBookMonth: true,
    }
    const rs: any = await confirmCheck(param)
    if (rs) {
      Message.success('核销成功')
      getTableList()
      return true
    }
    return false
  }
  // 取消核销
  async function onUnDoCheckBatch() {
    if (!selectIds.value.length) {
      Message.error('请选择数据')
      return
    }
    Modal.error({
      title: '确认',
      content: '请再次确认是否取消核销选中数据',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        let param = {
          adInvoiceIdList: selectIds.value,
          useAutoBookMonth: true,
        }
        let rs: any = await undoCheck(param)
        if (rs) {
          Message.success('取消核销成功')
          getTableList()
        }
      },
    })
  }
  async function onTestPullInvoice() {
    if (!filterData.value.shopIdList) {
      Message.error('请选择一个店铺!')
      return
    }
    let param = {
      shopId: filterData.value.shopIdList.split(',')[0],
    }

    testBody.value = null
    let rs: any = await checkShopSpStatus(param)
    if (rs) {
      testBody.value = rs?.body
      testResultDialog.value = true
    }
  }
  function onShowAdjustmentDistubutionDialog(item: any) {
    let totalAmt = item.adjustmentsList.map((item: any) => item.amt).reduce((a: number, b: number) => a + b, 0)
    showAdjustmentsDistubution.value = true
    countAutoDistubutionItem(item, totalAmt)
  }
  async function onShowTaxDistubutionDialog(item: any) {
    showTaxDistubution.value = true
    countAutoDistubutionItem(item, item.taxDueAmt || 0)
  }
  async function countAutoDistubutionItem(item: any, totalAmt: number) {
    const res: any = await getShopMarketAndUserInfo({
      id: item.shopId,
    })
    let shopUsers = res?.data?.shopUsers || []

    currentShopUserList.value = shopUsers.map((item: any) => {
      return {
        salesmanId: item.userId,
        salesmanName: item.userName,
        amt: 0,
      }
    })

    //总费用
    adjustmentTotalAmt.value = totalAmt

    //业务员费用比利
    let salesManCostMap = {}
    let totalCostAmt = 0
    item.totalItemAmtDetail.forEach((u: any) => {
      if (!salesManCostMap[u.salesmanId]) {
        salesManCostMap[u.salesmanId] = 0
      }
      salesManCostMap[u.salesmanId] += u.amt
      if (u.amt > 0) totalCostAmt += u.amt
    })
    delete salesManCostMap['unknow']
    let salesCostRate = {}
    for (let key in salesManCostMap) {
      if (salesManCostMap[key] > 0) {
        salesCostRate[key] = salesManCostMap[key] / totalCostAmt
      }
    }
    //均分
    let remainingAmt = adjustmentTotalAmt.value
    let oneUser: any = null
    currentShopUserList.value.forEach((u: any) => {
      let rate = salesCostRate[u.salesmanId]
      if (!rate) {
        return
      }
      u.amt = parseFloat((adjustmentTotalAmt.value * rate).toFixed(2))
      remainingAmt -= u.amt
      oneUser = u
    })
    if (oneUser && remainingAmt > 0) {
      oneUser.amt += remainingAmt
    } else if (oneUser && remainingAmt < 0) {
      oneUser.amt += remainingAmt
    }
    let fromMonth = item?.fromDate?.substring(0, 6)
    let toMonth = item?.toDate?.substring(0, 6)
    currentAllowMonth.value = []
    currentBookMonth.value = null
    if (fromMonth === toMonth) {
      currentBookMonth.value = fromMonth
      currentAllowMonth.value.push(fromMonth)
      let year = parseInt(fromMonth.substring(0, 4))
      let month = parseInt(fromMonth.substring(4))
      if (month < 12) {
        month++
        currentAllowMonth.value.push(year + '' + (month < 10 ? '0' + month : '' + month))
      } else {
        currentAllowMonth.value.push(year + 1 + '01')
      }
    } else {
      currentAllowMonth.value.push(fromMonth)
      currentAllowMonth.value.push(toMonth)
    }
    currentData.value = item
  }
  async function onConfirmCheck(type: string) {
    let items = currentShopUserList.value.filter((u) => u.amt != 0)
    let totalDisAmt = items.map((u) => u.amt).reduce((a, b) => a + b, 0)
    if (adjustmentTotalAmt.value.toFixed(2) != totalDisAmt.toFixed(2)) {
      Message.error('金额分配不正确!' + adjustmentTotalAmt.value + ' != ' + totalDisAmt)
      return
    }
    if (!currentBookMonth.value) {
      Message.error('请选择核入月份!')
      return
    }
    let requestItems = items.map((u) => {
      let disItem = {
        adInvoiceId: currentData.value.id,
        amt: u.amt,
        salesmanId: u.salesmanId,
        salesmanName: u.salesmanName,
        type: type,
      }
      return disItem
    })
    let rs = await adjustmentsDistribution({ item: requestItems })
    if (!rs) return
    Message.success('分配成功')
    let checkParam = {
      adInvoiceIdList: [currentData.value.id],
      bookMonth: currentBookMonth.value,
      useAutoBookMonth: true,
    }
    let res = await confirmCheck(checkParam)
    if (res) {
      Message.success('核销成功')
      showAdjustmentsDistubution.value = false
      showTaxDistubution.value = false
      getTableList()
    }
  }

  // 调整
  function onShowAddAdJustmentDialog(row: any) {
    currentData.value = row
    editAmt.value = 0
    editRemarks.value = ''
    addAdJustmentDialog.value = true
  }
  async function onSubmitAdjustment() {
    let param = {
      amt: editAmt.value,
      invoiceId: currentData.value.id,
      remarks: editRemarks.value,
    }
    const res: any = await adjustmentsAdd(param)
    if (!res) return false
    Message.success('增加成功')
    addAdJustmentDialog.value = false
    getTableList()
  }

  // 初始化查询
  function setDefaultSearch() {
    filterData.value = {
      marketplaceIdList: props.searchVal.marketplaceIdList,
      shopIdList: props.searchVal.shopIdList,
      checkStatus: '0',
    }
    getTableList()
  }
  // 显示店铺
  function getShopName(row: any) {
    return useBaseData.shopList?.find((item: any) => item.id === row.shopId)?.shopName || '未知'
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 设置查询条件
  function setSearchval() {
    let _params: any = JSON.parse(JSON.stringify(filterData.value))
    _params.invoiceIdList = _params.invoiceId?.trim() ? [_params.invoiceId?.trim()] : []
    _params.marketplaceIdList = _params?.marketplaceIdList ? _params.marketplaceIdList?.split(',') : []
    _params.shopIdList = _params.shopIdList ? _params.shopIdList?.split(',') : []

    if (_params?.bookMonth) {
      _params.checkStatus = 1
    }
    delete _params.invoiceId
    return _params
  }
  // 获取列表
  async function getTableList() {
    tableList.value = []
    const _param = {
      pageSize: searchVal.value.pageSize,
      pageNum: searchVal.value.pageNum,
      ...setSearchval(),
    }
    // 非管理员未选择店铺时默认传所有店铺
    if (!isAdmin.value && !_param.shopIdList?.length) {
      _param.shopIdList = useBaseData.shopList?.map((item: any) => item.id) || []
      if (!_param.shopIdList?.length) {
        Message.error('请选择店铺')
        return
      }
    }

    tableLoading.value = true
    tableRef.value.selectAll(false)
    const res: any = await invoiceFind(_param)
    seachData.value = _param.param
    emit('toSearch', filterData.value)
    tableLoading.value = false
    if (!res) return
    let list = res?.invoiceList || []
    total.value = res?.rows || 0
    tableListMap.value = {}
    list.forEach((item: any) => {
      item.adjustmentsAmt = item.adjustmentsAmt || 0
      tableListMap.value[item.id] = item
    })
    tableList.value = list
    let ids = tableList.value.map((item: any) => item.id)

    getSalesmanAmtCount(ids)
    getAdjustmentsFind(ids)
    getAccItemFind(ids)
  }
  async function getSalesmanAmtCount(ids: Array<any>) {
    const res: any = await salesmanAmtCount({ adInvoiceIdList: ids })
    let salesmanAmtList = res?.salesmanAmtList || []
    let map = {}
    salesmanAmtList.forEach((item: any) => {
      if (!map[item.adInvoiceId]) {
        map[item.adInvoiceId] = []
      }
      map[item.adInvoiceId].push(item)
    })
    tableList.value.forEach((item: any) => {
      item.totalItemAmtDetail = map[item.id] ? map[item.id] : []
    })
  }
  async function getAdjustmentsFind(ids: Array<any>) {
    const res: any = await adjustmentsFind({ adInvoiceIdList: ids })
    let adjustmentsList = res?.adjustmentsList || []
    let map = {}
    adjustmentsList.forEach((item: any) => {
      if (!map[item.adInvoiceId]) {
        map[item.adInvoiceId] = []
      }
      map[item.adInvoiceId].push(item)
    })
    tableList.value.forEach((item: any) => {
      item.adjustmentsList = map[item.id] ? map[item.id] : []
    })
  }
  async function getAccItemFind(ids: Array<any>) {
    const res: any = await accItemFind({ adInvoiceIdList: ids })
    let accItemList = res?.accItemList || []
    let map = {}
    accItemList.forEach((item: any) => {
      if (!map[item.adInvoiceId]) {
        map[item.adInvoiceId] = []
      }
      map[item.adInvoiceId].push(item)
    })
    tableList.value.forEach((item: any) => {
      item.accItemList = map[item.id] ? map[item.id] : []
    })
  }
  // 拉取
  async function onPullInvoiceItem(invoice: any) {
    let param = {
      requestList: [
        {
          companyId: invoice.companyId,
          shopId: invoice.shopId,
          invoiceId: invoice.invoiceId,
          invoiceDate: invoice.invoiceDate,
        },
      ],
    }
    let rs = await pullInvoiceItem(param)
    if (rs) {
      Message.success('已发起数据请求，5分钟后看结果')
    }
  }

  // 打开明细报告
  function openDetail(row: any) {
    emit('openDetail', row.invoiceId)
  }
</script>

<style lang="less" scoped>
  .adInvoice-report-list {
    height: calc(100vh - @menuAndTabHeight);
    .sales-man {
      margin-left: 10px;
      width: 110px;
      display: inline-block;
      .sales-man-name {
        color: rgb(143, 140, 140);
      }
      .sales-man-amt {
        font-size: 14px;
        margin-left: 5px;
      }
    }
  }
  .adjustments-list-header {
    padding: 10px;
    background: #f7f8fa;
    font-size: 12px;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
  .adjustments-list-con {
    li {
      padding: 10px;
      font-size: 12px;
      text-align: center;
      border-bottom: 1px solid #ebeef5;
      &:last-child {
        border-bottom: none;
      }
    }
  }
  .add-adjustment-w {
    .label {
      width: 80px;
      flex-shrink: 0;
    }
    .adjustment-id {
      margin-bottom: 20px;
    }
    .item {
      margin-bottom: 20px;
    }
  }
  .allot-w {
    height: calc(84vh - 160px);
    overflow-y: auto;
    h4 {
      font-weight: bold;
      color: #666;
      margin-bottom: 5px;
    }
    .arco-alert {
      margin: 10px 0;
    }
  }
</style>
